//
//  HEGridImageView.m
//  HealthFamily
//
//  Created by 吴欧 on 2020/12/9.
//  Copyright © 2020 honglutec. All rights reserved.
//

#import "HEGridImageView.h"
#import "KNPhotoBrowser.h"

@interface HEGridImageView ()<KNPhotoBrowserDelegate>

@property (nonatomic, strong) NSMutableArray *ButtonArray;
@property (nonatomic, strong) NSMutableArray *itemsArr;
@property (nonatomic, strong) KNPhotoBrowser *photoBrowser;

@property (nonatomic, assign) CGFloat fixedSpacing;
@property (nonatomic, assign) CGFloat leadSpacing;
@property (nonatomic, assign) CGFloat tailSpacing;
@property (nonatomic, assign) CGFloat itemWidth;

@end

static CGFloat margin = 10.f;

@implementation HEGridImageView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        
        _fixedSpacing = 10.f;
    }
    return self;
}

- (void)shwoViewWithFixedSpacing:(CGFloat)fixedSpacing leadSpacing:(CGFloat)leadSpacing tailSpacing:(CGFloat)tailSpacing contentWidth:(CGFloat)width {
    _fixedSpacing = fixedSpacing;
    _leadSpacing = leadSpacing;
    _tailSpacing = tailSpacing;
    
    _itemWidth = (width - fixedSpacing * 2 - leadSpacing - tailSpacing ) / 3.0;
    
    [self setUpUI];

    [self renderImage];
}

- (void)shwoViewWithFixedSpacing:(CGFloat)fixedSpacing leadSpacing:(CGFloat)leadSpacing tailSpacing:(CGFloat)tailSpacing {
    _fixedSpacing = fixedSpacing;
    _leadSpacing = leadSpacing;
    _tailSpacing = tailSpacing;
    
    _itemWidth = (KScreenWidth - fixedSpacing * 2 - leadSpacing - tailSpacing ) / 3.0;
    
    [self setUpUI];

    [self renderImage];
}

-(void)setUpUI {
   
//    NSInteger line = self.imagesArray.count%3;
    for (int i = 0; i < 9; i++) {
        
        NSInteger row1 = i/3;
        NSInteger colum = i%3;
        
        UIImageView *imageView = [[UIImageView alloc] init];
        [imageView setUserInteractionEnabled:YES];
        [imageView setBackgroundColor:[UIColor grayColor]];
        [imageView setContentMode:UIViewContentModeTop | UIViewContentModeLeft | UIViewContentModeRight];
        imageView.contentMode = UIViewContentModeScaleAspectFill;
        imageView.clipsToBounds = YES;
        imageView.frame = CGRectMake((_fixedSpacing + _itemWidth )*colum + _leadSpacing, (_fixedSpacing + _itemWidth)*row1, _itemWidth, _itemWidth);
        imageView.hidden = YES;
        imageView.tag = i;
        imageView.contentMode = UIViewContentModeScaleAspectFill;
        
        [self.ButtonArray addObject:imageView];
        [self addSubview:imageView];
    }
}

-(void)setImagesArray:(NSMutableArray *)imagesArray {
    _imagesArray = imagesArray;
}

- (void)renderImage {
    NSInteger count = (_imagesArray.count - 1)/3  +1;
       
   [self.itemsArr removeAllObjects];
   [self.ButtonArray enumerateObjectsUsingBlock:^(UIButton *  _Nonnull button, NSUInteger idx, BOOL * _Nonnull stop) {
       
       if (idx<self.imagesArray.count) {
           
           button.hidden = NO;
           UIImageView *imageView = self.ButtonArray[idx];
           [imageView sd_setImageWithURL:[NSURL URLWithString:self.imagesArray[idx]] placeholderImage:[UIImage imageNamed:@"noImage"]];

           KNPhotoItems *items = [[KNPhotoItems alloc] init];
           items.url = _imagesArray[idx];
           items.sourceView = imageView;
           [self.itemsArr addObject:items];
           
           UITapGestureRecognizer *tapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(bigImage:)];
           imageView.userInteractionEnabled=YES;
           [imageView addGestureRecognizer:tapGes];
           
       }else{
           button.hidden = YES;
       }
   }];
   
   if (_imagesArray.count == 0) {
       [self mas_updateConstraints:^(MASConstraintMaker *make) {
           make.height.mas_equalTo(0).priorityMedium();
       }];
   }else{
       [self mas_updateConstraints:^(MASConstraintMaker *make) {
           make.height.mas_equalTo((_fixedSpacing + _itemWidth)*count).priorityMedium();
       }];
   }
}


#pragma mark - Getter

- (NSMutableArray *)ButtonArray {
    if(!_ButtonArray){
        _ButtonArray = [[NSMutableArray alloc] init];
    }
    return _ButtonArray;
}

#pragma mark -
- (NSMutableArray *)itemsArr {
    if (!_itemsArr) {
        _itemsArr = [NSMutableArray array];
    }
    return _itemsArr;
}

- (void)bigImage:(UITapGestureRecognizer *)tap {
 
    KNPhotoBrowser *photoBrowser = [[KNPhotoBrowser alloc] init];
    photoBrowser.itemsArr = [self.itemsArr copy];
    photoBrowser.isNeedPageNumView = true;
    photoBrowser.isNeedRightTopBtn = true;
    photoBrowser.isNeedPictureLongPress = true;
    photoBrowser.isNeedPanGesture = true;
    photoBrowser.isNeedPrefetch = true;
    photoBrowser.isNeedAutoPlay = true;
    photoBrowser.currentIndex = tap.view.tag;
    photoBrowser.delegate = self;
    [photoBrowser present];
    
    _photoBrowser = photoBrowser;
}

/* photoBrowser 右上角按钮的点击 */
- (void)photoBrowserRightOperationAction{
    
    __weak typeof(self) weakself = self;
    KNActionSheet *actionSheet = [[KNActionSheet share] initWithTitle:@"" cancelTitle:@"" titleArray:@[@"保存"].mutableCopy destructiveArray:@[@"0"].mutableCopy actionSheetBlock:^(NSInteger buttonIndex) {
        if (buttonIndex == 0) {
 
            [weakself toSaveImage:[NSURL URLWithString:weakself.photoBrowser.itemsArr[weakself.photoBrowser.currentIndex].url]];
        }
    }];
    
    [actionSheet show];
}

/// long press
/// @param photoBrowser pb
/// @param longPress press
- (void)photoBrowser:(KNPhotoBrowser *)photoBrowser longPress:(UILongPressGestureRecognizer *)longPress {
    if (longPress.state == UIGestureRecognizerStateBegan) {
        [photoBrowser setImmediatelyPlayerRate:2];
    }else if (longPress.state == UIGestureRecognizerStateEnded || longPress.state == UIGestureRecognizerStateCancelled || longPress.state == UIGestureRecognizerStateFailed || longPress.state == UIGestureRecognizerStateRecognized){
        [photoBrowser setImmediatelyPlayerRate:1];
    }
}


- (void)toSaveImage:(NSURL *)url {
    SDWebImageManager *manager = [SDWebImageManager sharedManager];
    if ([manager cacheKeyForURL:url]) {
       [[manager imageCache] queryImageForKey:url.absoluteString options:SDWebImageFromCacheOnly context:nil completion:^(UIImage * _Nullable image, NSData * _Nullable data, SDImageCacheType cacheType) {
           // 保存图片到相册中
           UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
        }];
        return;
    }
    else {
        //从网络下载图片
        NSData *data = [NSData dataWithContentsOfURL:url];
        UIImage *img = [UIImage imageWithData:data];
        // 保存图片到相册中
        UIImageWriteToSavedPhotosAlbum(img,self, @selector(image:didFinishSavingWithError:contextInfo:),nil);
    }
}

//保存图片完成之后的回调
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error
  contextInfo:(void *)contextInfo {
    if (error != NULL) {
        [Dialog toast:@"图片保存失败" delay:2.0];
    }
    else  // No errors
    {
        [Dialog toast:@"图片保存成功" delay:2.0];
    }
}



@end

